# @Time: 2022/3/23 19:50
# @Author: HeYuanqing
# @Reference: http://www.blackpawn.com/texts/pointinpoly/default.html
def point_minus(point1, point2):
    point3 = [point1[0] - point2[0], point1[1] - point2[1]]
    return point3


def point_dot(point1, point2):
    return point1[0] * point2[0] + point1[1] * point2[1]


def point_cross(point1, point2):
    return point1[0] * point2[1] - point1[1] * point2[0]


def point_in_triangle(A, B, C, P):
    v0 = point_minus(C, A)
    v1 = point_minus(B, A)
    v2 = point_minus(P, A)

    dot00 = point_dot(v0, v0)
    dot01 = point_dot(v0, v1)
    dot02 = point_dot(v0, v2)
    dot11 = point_dot(v1, v1)
    dot12 = point_dot(v1, v2)

    inverDeno = 1 / (dot00 * dot11 - dot01 * dot01)
    u = (dot11 * dot02 - dot01 * dot12) * inverDeno
    if u < 0:  # if u out of range, return directly
        return False
    if u > 1:
        return False

    v = (dot00 * dot12 - dot01 * dot02) * inverDeno

    if v < 0:  # if v out of range, return directly
        return False
    if v > 1:
        return False
    if u + v < 1:
        return True
    else:
        return False


if __name__ == '__main__':
    a = [1, 0]
    b = [0, 0]
    c = [0, 1]
    p = [0.5, 0.2]
    # True 表示点在三角形内，False表示在三角形外
    containerPoint = point_in_triangle(a, b, c, p)
    print(containerPoint)
